package com.dating.base.module;

import java.util.List;

import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.dating.base.bean.Role;
import com.dating.base.bean.User.Type;
import com.dating.base.service.RoleService;
import com.dating.core.entries.Result;
import com.dating.core.ext.BaseModule;

public class RoleModule extends BaseModule {


	@Inject
	private RoleService roleService ;
	
	@Override
	public String _getNameSpace() {
		return "role";
	}
	
	@At("role/list")
	@Ok("beetl:templates/pages/base/roles.html")
	public Result list(){
		List<Role> roles = roleService.getAllByParam(Mvcs.getReq().getParameter("key"));
		return Result.success().addData("roles", roles);
	}
	
	
	/**
	 * 查询所有的角色
	 * @return
	 */
	@At("role/all")
	@Ok("json")
	public Result allRoles(){
		List<Role> roles = roleService.getAllByParam(Mvcs.getReq().getParameter("key"));
		return Result.success().addData("roles", roles);
	}
	
	
	/**
	 * to 编辑页
	 * @return
	 */
	@At("role/toEdit")
	@Ok("json")
	public Result toEdit(int id){
		Role role = roleService.findByid(id);
		return Result.success().addData("role", role);
	}
	
	/**
	 * 添加角色
	 * @param role
	 * @return
	 */
	@At("role/add")
	@Ok("json")
	public Result add(@Param("..")Role role){
		Role tRole = roleService.findByName(role.getName());
		if(tRole == null){
			roleService.save(role);
		}else{
			return Result.fail(String.format("角色Key%s已存在", role.getName()));
		}
		return Result.success().addData("role", role);
	}
	
	
	/**
	 * 修改角色
	 * @param role
	 * @return
	 */
	@At("role/update")
	@Ok("json")
	public Result update(@Param("..")Role role){
		Role tRole = roleService.findByName(role.getName());
		if(tRole == null || tRole.getId().equals(role.getId())){
			roleService.updateIgnoreNull(role);
		}else{
			return Result.fail(String.format("角色Key%s已存在", role.getName()));
		}
		return Result.success().addData("role", role);
	}

	
	/**
	 * 删除指定id的角色
	 * @param ids
	 * @return
	 */
	@At("role/batchDel")
	@Ok("json")
	public Result update(String ids){
		roleService.batchDel(ids);
		return Result.success();
	}
	
	
	/**
	 * 查询用户角色
	 * @param uid
	 * @return
	 */
	@At("role/userRole")
	@Ok("json")
	public Result userRoles(Integer uid){
		List<Role> roles = roleService.findByUserId(uid, Type.PLATFORM);
		return Result.success().addData("roles", roles);
	}
}
